﻿using AutoMapper;
using MD5Hash;
using MediatR;
using RBAC_Uthorization.API.Application.Command.UserInfoCommand;
using RBAC_Uthorization.API.DTO;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Domain.Entity;
using RBAC_Uthorization.Infrstructre.Interface;

namespace RBAC_Uthorization.API.Application.CommandHandlers.UserInfoHandler
{
    public class UserloginCreateCommandHandlers : IRequestHandler<UserloginCreateCommand, ApiResult<int>>
    {
        private readonly IMapper _mapper;
        private readonly IOfficRepository _officRepository;
        private readonly IUserInfoRepository _userInfoRepository;
        private readonly ILogger<UserloginCreateCommandHandlers> _logger;

        public UserloginCreateCommandHandlers(IMapper mapper, IUserInfoRepository userInfoRepository, ILogger<UserloginCreateCommandHandlers> logger, IOfficRepository officRepository)
        {
            _mapper = mapper;
            _userInfoRepository = userInfoRepository;
            _logger = logger;
            _officRepository = officRepository;
        }

        public async Task<ApiResult<int>> Handle(UserloginCreateCommand request, CancellationToken cancellationToken)
        {
            try
            {

                // 查询用户是否存在
                var user = await _userInfoRepository.GetAllAsync();
                var offlc= await _officRepository.GetbyIdAsync(request.offlcid);
                if (user.Any(x => x.login_name == request.dto.login_name&&x.del_flag==0))
                {
                    _logger.LogError($"创建人:{request.createname},用户已存在:{request.dto.login_name}");
                    return new ApiResult<int>() { Code = ResultCode.Created, Message = "用户已存在" };
                }
                if (user.Any(x => x.login_name == request.dto.login_name && x.del_flag == 1))
                {
                    _logger.LogError($"创建人:{request.createname},用户已注销:{request.dto.login_name}用户Id:{user[0].id}用户已注销,想恢复请联系系统管理员");
                    return new ApiResult<int>() { Code = ResultCode.Created, Message = "用户已注销,想恢复请联系系统管理员" };
                }
                //创建用户
                var usermap = _mapper.Map<sys_user>(request.dto);
                usermap.offic_id = request.offlcid;
                usermap.password = request.dto.password.GetMD5();
                usermap.create_by = request.createname;
                usermap.create_date = DateTime.UtcNow;
                usermap.sys_id = request.sys_id;
                var entity = await _userInfoRepository.AddAsync(usermap);
                if (entity == null)
                {
                    _logger.LogError($"创建人:{request.createname},创建用户失败数据:{request.dto}");
                    return new ApiResult<int>() { Code = ResultCode.Fail, Message = "创建失败" };
                }
                //给公司新增员工数量
                offlc.num += 1;
                var offlcs = await _officRepository.UpdateAsync(offlc);
                // 记录成功日志
                _logger.LogInformation($"创建人：{request.createname}用户新增成功:{usermap.id},{usermap.name}");

                return new ApiResult<int>();



            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "新增用户创建失败异常");
                return new ApiResult<int>() { Code = ResultCode.Fail, Message = "新增用户创建失败异常" };
            }
        }
    }
}
